package com.hotelbooking.mc;

import java.util.List;

import com.hotelbooking.db.PartDbManager;
import com.hotelbooking.db.TableMapper;
import com.hotelbooking.db.define.TablePartUnit;
import com.hotelbooking.user.data.User;

public class UserMcManager {
	protected static final UserMcManager instance = new UserMcManager();

	private static final String selectUserName = "SELECT UserId,UserName FROM User%s";

	private static final String keyPrefix = "un_%s";

	static {
		initName2Id();
	}

	private static void initName2Id() {
		int tablePartUnit = TablePartUnit.getTablePartUnit("User");
		int sum = 1000 / tablePartUnit;
		for (int index = 0; index < sum; index++) {
			PartDbManager partDbManager = TableMapper.mapByTableIndex(
					selectUserName, index);
			List<User> list = partDbManager.executeSqlQuery(User.class);
			for (User user : list) {
				MemCachedManager.instance.replace(getMcKey(user.getName()),
						user.getUserId());
			}
		}
	}

	private static String getMcKey(String userName) {
		return String.format(keyPrefix, userName);
	}

	public int getIdByUserName(String userName) {
		Object userId = MemCachedManager.instance.get(getMcKey(userName));
		if (userId == null) {
			return 0;
		}
		return (Integer) userId;
	}
}
